'''
Created on Apr 15, 2012

@author: Vu Dao
'''
from selenium import webdriver
from Interface.categoryPage import xpathNewCategory, xpathTxtNewCategory,\
    xpathComboNewCategory, xpathSubmitNewCategoryButton, xpathTxtSearchCategory,\
    xpathCategoryName, xpathDeleteCategory
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.keys import Keys

# Click on new category button
def clickOnNewCategory(self):
    browser=self.browser
    elem = browser.find_element_by_xpath(xpathNewCategory())
    elem.click()
    browser.implicitly_wait(60)
    
# create a new category
def createNewCategory(self,categoryName,categoryType="----Root category----"):
    browser=self.browser
    # input new category name
    elem = browser.find_element_by_xpath(xpathTxtNewCategory())
    elem.clear()
    elem.send_keys(categoryName)
    # select type category
    elem = browser.find_element_by_xpath(xpathComboNewCategory())
    Select(elem).select_by_visible_text(categoryType)
    # click on submit button
    elem = browser.find_element_by_xpath(xpathSubmitNewCategoryButton())
    elem.click()
    browser.implicitly_wait(60)
    
# verify a category is created successfully
def isCategoryCreatedSuccessfully(self,categoryName):
    browser=self.browser
    try:
        WebDriverWait(browser,20).until(lambda browser : browser.find_element_by_xpath("//span[contains(text(),'"+categoryName+"')]"))
        return True
    except:
        return False
    
# search category
def searchCategory(self,categoryName):
    browser=self.browser
    elem = browser.find_element_by_xpath(xpathTxtSearchCategory())
    elem.clear()
    elem.send_keys(categoryName)
    elem.send_keys(Keys.RETURN)
    
# click on category name
def clickOnCategoryName(self,categoryName):
    browser=self.browser
    elem = browser.find_element_by_xpath(xpathCategoryName(categoryName))
    elem.click()
    
# delete a category
def deleteCategory(self,categoryName):
    browser=self.browser
    elem = browser.find_element_by_xpath(xpathDeleteCategory(categoryName))
    elem.click()
    # process popup
    alert = browser.switch_to_alert()
    alert.accept()
    browser.refresh()
    browser.implicitly_wait(60)